class ArticlesController < ApplicationController
  before_filter :find_article_by_params, :only => [:show, :sortable, :update_sortable, :edit, :update]
  before_filter :authenticate, :except => [:index, :list, :show]
  
  def new
    @article = Article.new
  end  
  
  def sortable
    render :action => :show
  end
  
  def create
    @article = Article.new(params[:article])
    if @article.save
      update_contents(params[:contents]) if params[:contents]
      redirect_to_admin
    else
      render :action => :new
    end
  end  
  
  def update
    if @article.update_attributes(params[:article])
      update_contents(params[:contents]) if params[:contents]
      redirect_to :action => :show, :id => @article
    else
      render :action => :edit
    end
  end
  
  def remove_content
    if request.xhr?
      content = Content.find(params[:id])
      content.destroy
      render :text => "" 
    end
  end
  
  def update_sortable
    Content.sortable(params[:items])
    render :file => "articles/update_sortable.js"
  end
  
  protected
  
    def update_contents(contents)
      unless contents[:id].size.zero?
        contents[:id].each_with_index do |id, i|
          attributes = {:body => contents[:body][i], :language_type => contents[:language_type][i]}
          if id.blank?
            @article.contents.create(attributes) unless contents[:body][i].blank?
          else
            @article.contents.find(contents[:id][i]).update_attributes(attributes)
          end
        end
      end
    end
  
  private
    
    def find_article_by_params
      @article = Article.find(params[:id])   
    end
end